

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <pthread.h>

using namespace std;

namespace Client
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR

    };
    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _sockfd(-1), _quit(false)
        {
        }
        void InitClient()
        {
            // 创建套接字
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error" << ":" << errno << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            // 客户端需要bind，但是不需要明确的用户显式的去bind
        }
        static void *readMessage(void *args)
        {
            int _sockfd = *(static_cast<int *>(args));
            pthread_detach(pthread_self());
            while (true)
            {
                char buffer[1024];
                sockaddr_in tmp;
                socklen_t tmp_len = sizeof(tmp);
                size_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &tmp_len);
                if (n > 0)
                    buffer[n] = 0;
                cout << buffer << endl;
                // cout << "服务器的翻译结果# " << buffer << endl;
            }
        }
        void Run()
        {
            pthread_create(&_reader, nullptr, readMessage, (void *)&_sockfd);

            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            socklen_t len = sizeof(server);
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            string message;
            char cmdline[1024];
            while (!_quit)
            {
                // cout << "Please Enter# ";
                // cin >> message;
                fprintf(stderr, "Enter# "); // 凡是用户输出的都往2号文件描述符中输出
                fflush(stderr);
                fgets(cmdline, sizeof(cmdline), stdin);
                cmdline[strlen(cmdline) - 1] = 0; // 输入online会摁回车
                message = cmdline;
                sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, len);
            }
        }
        ~udpClient()
        {
        }

    private:
        uint16_t _serverport;
        string _serverip;
        int _sockfd;
        bool _quit;
        pthread_t _reader;
    };
}